package com.example.contact;

import java.net.ContentHandler;
import java.util.ArrayList;
import java.util.HashMap;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper extends SQLiteOpenHelper {
	
	public final static String DB_NAME="contact";
	public final static int VERSION = 7;
	
	private static DBHelper instance = null;
	
	private SQLiteDatabase db;
	
	public static DBHelper getInstance(Context context) {
		if(instance == null) {
			instance = new DBHelper(context);
		}
		return instance;
	}
	
	private void openDataBase() {
		if(db == null) {
			db = this.getWritableDatabase();
		}
	}
	
	private DBHelper(Context context) {
		super(context, DB_NAME, null, VERSION);
	}
	

	public void onCreate(SQLiteDatabase db) {
		StringBuffer tableCreate = new StringBuffer();
		tableCreate.append("create table user (_id integer primary key autoincrement,")
					.append("name text,")
					.append("imageid int,")
					.append("mytext text)");
		db.execSQL(tableCreate.toString());
	}
	
	public long save(User user) {
		
		openDataBase();
		ContentValues value = new ContentValues();
		value.put("imageid", user.imageId);
		value.put("name", user.name);
		value.put("mytext", user.mytext);
		
		return db.insert("user", null, value);
		
	}

	public long delete(int id) {
		openDataBase();
		return db.delete("user", "_id=?", new String []{Integer.toString(id)});
	}
	
	public long upDate (User user) {
		openDataBase();
		ContentValues value = new ContentValues();
		value.put("name", user.name);
		value.put("mytext", user.mytext);
		return db.update("user", value, "name = ?", new String[]{user.name});
	}
	
	public ArrayList getUserList() {
		openDataBase();
		Cursor cursor = db.query("user", null, null, null, null, null, null);
		ArrayList list = new ArrayList();
		while(cursor.moveToNext()) {
			HashMap map =new HashMap();
			map.put("_id", cursor.getInt(cursor.getColumnIndex("_id")));
			map.put("imageid", cursor.getInt(cursor.getColumnIndex("imageid")));
			map.put("name", cursor.getString(cursor.getColumnIndex("name")));
			map.put("mytext", cursor.getString(cursor.getColumnIndex("mytext")));
			list.add(map);
		}
		return list;
	}
	
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		String sql = "drop table if exists user";
		db.execSQL(sql);
		onCreate(db);
	}

}
